package tk.heimashuma.store.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import tk.heimashuma.store.entity.Addrs;
import tk.heimashuma.store.entity.Commodity;
import tk.heimashuma.store.entity.Transaction;
import tk.heimashuma.store.entity.Users;
import tk.heimashuma.store.service.PayService;
import tk.heimashuma.store.service.UserInfoService;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private PayService payService;
    @Autowired
    private UserInfoService userInfoService;
    @GetMapping("/check/{t_id}")
    public String toPay(@PathVariable String t_id, HttpSession session, Map<String,Object> map){
        Object o = session.getAttribute("user");
        Users user = (Users) o;
        Object currentCar = session.getAttribute("currentCar");
        session.removeAttribute("currentCar");
        Transaction transaction = payService.findTranSaction(t_id);
        List<Addrs> addrsList = userInfoService.findAddrByUser(user);
        map.put("currentCar",currentCar);
        map.put("addr",addrsList);
        transaction.setCommodityList(null);
        map.put("info",transaction);
        return "/pay/zhifu";
    }
    @GetMapping("/toPay/{tid}/{aid}")
    public String  toPagePay(Map<String, Object> map, @PathVariable String tid, @PathVariable Integer aid){
        payService.bindAddr(tid,aid);
        map.put("tId",tid);
        return "/pay/gotoPagePay";
    }
    @GetMapping("/payOne/{cid}/{num}")
    public String toPagePay(@PathVariable Integer cid,@PathVariable Integer num,HttpSession session,Map<String,Object>map){
        Object o = session.getAttribute("user");
        Users user = (Users) o;
        Optional<Commodity> commodity = payService.findCommodityById(cid);
        if(commodity.isPresent()){
            Transaction transaction = payService.createOneOrder(commodity.get(),num,user);
            List<Addrs> addrsList = userInfoService.findAddrByUser(user);
            map.put("addr",addrsList);
            map.put("info",transaction);
            map.put("num",num);
            return "/pay/zhifu";
        }
        return null;
    }
}
